// pages/handlerQuote/index.js
const api = require('../../../utils/request.js') 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasAuth: true,
    designerID: null,
    address: null,
    multiArray: [
      ['0室', '1室', '2室', '3室', '4室', '5室', '6室', '7室', '8室', '9室', '10室'],
      ['0厅', '1厅', '2厅', '3厅', '4厅', '5厅', '6厅', '7厅', '8厅', '9厅', '10厅'],
      ['0厨', '1厨', '2厨', '3厨', '4厨', '5厨', '6厨', '7厨', '8厨', '9厨', '10厨'],
      ['0卫', '1卫', '2卫', '3卫', '4卫', '5卫', '6卫', '7卫', '8卫', '9卫', '10卫'],
      ['0阳台', '1阳台', '2阳台', '3阳台', '4阳台', '5阳台', '6阳台', '7阳台', '8阳台', '9阳台', '10阳台']
    ],
    multiIndex: [1, 1, 1, 1, 1],
    imgCount: 8,
    imgList: []
  },
  MultiChange(e) {
    this.setData({
      multiIndex: e.detail.value
    })
  },
  addressChange: function (e) {
    const that = this
    wx.chooseLocation({
      success(res) {
        that.setData({
          address: res
        })
      },
      fail (e) {
        if (e.errMsg === 'chooseLocation:fail auth deny' || e.errMsg === 'chooseLocation:fail authorize no response') {
          that.setData({
            hasAuth: false
          })
        }
      }
    })
  },
  hasAuthChange({ detail }) {
    this.setData({
      'hasAuth': detail
    })
  },
  ChooseImage() {
    const that = this
    wx.chooseImage({
      count: that.data.imgCount - that.data.imgList.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        that.setData({
          imgList: [
            ...that.data.imgList,
            ...res.tempFilePaths
          ]
        })
      }
    });
  },
  uploadImage(filePath) {
    return new Promise(resolve => {
      wx.uploadFile({
        url: `${api.IMG_HOST}/File/Upload`,
        method: 'POST',
        filePath: filePath,
        name: 'files',
        header: {
          'content-type': 'multipart/form-data',
          'shopID': wx.getStorageSync('shopID') || 1,
          'token': wx.getStorageSync('Token') || '',
        },
        success(res) {
          resolve(res)
        },
        complete() {
          wx.hideLoading()
        },
        fail() {
          
        }
      })
    })
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    this.data.imgList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgList: this.data.imgList
    })
  },
  formSubmit ({detail}) {
    if (this.data.address === null) {
      wx.showToast({
        icon: 'none',
        title: '请先选择地址'
      })
      return false
    }
    if (!detail.value.roomSize) {
      wx.showToast({
        icon: 'none',
        title: '请先填写面积'
      })
      return false
    }
    this.reserveDesigner({
      Address: `${this.data.address.address}-${this.data.address.name}`,
      Rooms: detail.value.layout,
      roomSize: detail.value.roomSize,
      Imgs: this.data.imgList
    })
  },
  reserveDesigner({ Address = "", Rooms = [], roomSize, Imgs = "" }) {
    let imgPromise = []
    let imgList = []
    if (Imgs && Imgs.length > 0) {
      wx.showLoading({
        title: '正在上传户型图',
        mask: true
      })
      Imgs.map(item => {
        imgPromise.push(
          this.uploadImage(item).then(res => {
            if (res.statusCode === 200) {
              imgList.push(JSON.parse(res.data).data.objectId)
            }
          })
        )
      })
    }
    Promise.all(
      imgPromise
    ).then(() => {
      wx.hideLoading()
      wx.showLoading({
        title: '预约中',
        mask: true
      })
      return new Promise(resolve => {
        api._post('/User/Design/Reserve', {
          DesignerID: this.data.designerID,
          Address: Address,
          Rooms: Rooms,
          Imgs: imgList.join(','),
          acreage: parseFloat(roomSize) || 0,
          Description: ''
        }, {
            loading: false
          }).then(res => {
            wx.hideLoading()
            if (res.Code === 100000) {
              wx.redirectTo({
                url: '/pages/orders/list/index'
              })
              resolve()
            } else {
              wx.showToast({
                icon: 'none',
                title: res.Msg
              })
            }
          })
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ designerID }) {
    this.setData({
      designerID: designerID
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})